<?php
/**
 * Created by PhpStorm.
 * 考试日历
 * Time: 17:04
 */
namespace app\modules\content\controllers;

use app\libs\GetData;
use app\libs\Pager;
use app\modules\content\models\Calendar;
use yii;
use app\libs\ApiControl;

class CalendarController extends ApiControl
{
    public $enableCsrfValidation = false;

    public function actionIndex()
    {
        $page = Yii::$app->request->get('page', 1);
        $year = Yii::$app->request->get('year');
        $month = Yii::$app->request->get('month');
        $where = ' 1=1';
        if ($year != false) {
            $where .= " and year= $year";
        }
        if ($month != false) {
            $where .= " and month= $month";
        }
        $offset = ($page - 1) * 15;
        $data = Calendar::find()->asArray()->where($where)->offset($offset)->limit(15)->orderBy('id desc')->all();
        $count = Yii::$app->db->createCommand("select count(*) as count from {{%calendar}} where $where")->queryOne();
        $url = strstr($_SERVER['REQUEST_URI'], '?') == false ? $_SERVER['REQUEST_URI'] . '?page' : $_SERVER['REQUEST_URI'] . '&page';
        $count = $count['count'];
        $page = new Pager("$url", $count, $page, 15);
        $str = $page->GetPager();
        return $this->render('index', ['data' => $data, 'str' => $str]);

    }

    public function actionAdd()
    {
        if (!$_POST) {
            $id = Yii::$app->request->get('id', '');
            if (empty($id)) {
                return $this->render('add');
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%calendar}} where id=" . $id)->queryOne();
                return $this->render('add', ['data' => $data]);
            }

        } else {
            $model = new Calendar();
            $data = Yii::$app->request->post();
            $data['endTime'] = strtotime($data['endTime']);
            $data['printTime'] = strtotime($data['printTime']);
            $data['sendTime'] = strtotime($data['sendTime']);
            $data['createTime'] = time();
            unset($data['_csrf']);
            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%calendar}}", $data)->execute();
            } else {
                $re = $model->updateAll($data, 'id=:id', array(':id' => $data['id']));
            }
            if ($re) {
                $this->redirect('index');
            } else {
                echo '<script>alert("数据修改/添加失败，请重试");history.go(-1);</script>';
                die;
            }
        }

    }

}